package com.atguigu.dga.governance.assess.quality;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskInstance;
import com.atguigu.dga.ds.service.TDsTaskInstanceService;
import com.atguigu.dga.governance.assess.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import com.atguigu.dga.meta.bean.TableMetaInfo;
import com.atguigu.dga.meta.constant.CodeConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component("TIME_LINESS")
public class TimeLinessAssessor extends Assessor {

    //当日产出时效，超过前{days}天产出时效平均值{percent}%
    //则给0分，其余10分

    //  1 求当天的平均耗时

    // 2  求前n天的平均耗时  需要计算前n天起止日期

    // 3  就 求当天的平均耗时 -前n天的平均耗时 / 前n天的平均耗时

    //4  占比 和  参考占比 比大小     如果超过 则给差评


    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;
    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws Exception {



        List<TDsTaskInstance> dsTaskInstanceList = assessParam.getTDsTaskInstanceList();
        if(dsTaskInstanceList==null){
            return;
        }
        Long curTotalDurationSec=0L;
        Integer successTaskCount=0;
        for (TDsTaskInstance tDsTaskInstance : dsTaskInstanceList) {
            if(tDsTaskInstance.getState().intValue()== CodeConst.TASK_STATE_SUCCESS){
                long taskDurationMs = tDsTaskInstance.getEndTime().getTime() - tDsTaskInstance.getSubmitTime().getTime();
                curTotalDurationSec+=taskDurationMs/1000L;
                successTaskCount++;
            }
        }
        //当日的平均耗时
        BigDecimal curAvgDurationSec= BigDecimal.valueOf(curTotalDurationSec).divide( BigDecimal.valueOf(successTaskCount),1,BigDecimal.ROUND_HALF_UP);

        // 提取天数
        String metricParamsJson = assessParam.getGovernanceMetric().getMetricParamsJson();
        JSONObject paramJsonObj = JSON.parseObject(metricParamsJson);
        Integer days = paramJsonObj.getInteger("days");
        //求 时间范围
        String assessDate = assessParam.getAssessDate();
        Date assessDateDt = DateUtils.parseDate(assessDate, "yyyy-MM-dd");
        String fromDt = DateFormatUtils.format(DateUtils.addDays(assessDateDt,  -days),"yyyy-MM-dd") ;
        String EndDt = DateFormatUtils.format(DateUtils.addDays(assessDateDt,  -1),"yyyy-MM-dd") ;


        // 查询任务列表的条件： 1 当前库名.表名  2 成功的任务 3  时间范围  between
        TableMetaInfo tableMetaInfo = assessParam.getTableMetaInfo();
        QueryWrapper<TDsTaskInstance> queryWrapper = new QueryWrapper<TDsTaskInstance>().eq("name", tableMetaInfo.getSchemaName() + "." + tableMetaInfo.getTableName())
                .eq("state", CodeConst.TASK_STATE_SUCCESS)
                .between("submit_time", fromDt, EndDt)
                .select(" avg(end_time -submit_time) as avg_duration_sec ")
                ;
        Map<String, Object> resultMap = tDsTaskInstanceService.getMap(queryWrapper);
        BigDecimal avgDurationSecN =(BigDecimal) resultMap.get("avg_duration_sec");
        if(avgDurationSecN==null||avgDurationSecN.equals(BigDecimal.ZERO)){
            return;
        }

        // 3  就 求当天的平均耗时 -前n天的平均耗时 / 前n天的平均耗时

        BigDecimal durationPercent = curAvgDurationSec.subtract(avgDurationSecN).movePointRight(2).divide(avgDurationSecN, 1, BigDecimal.ROUND_HALF_UP);
        //4  占比 和  参考占比 比大小     如果超过 则给差评
        BigDecimal paramPercent = paramJsonObj.getBigDecimal("percent");

        if(durationPercent.compareTo(paramPercent)>0){ //前大后小 给差评
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("超过"+days+"天平均耗时"+durationPercent+"%  [当日平均耗时:"+curAvgDurationSec+"s,前n天平均耗时："+avgDurationSecN+"s]"  );

        }


    }
}
